package com.ghd.dataviz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ghd.dataviz.core.exception.BusinessException;
import com.ghd.dataviz.core.param.PageInfo;
import com.ghd.dataviz.entity.User;
import com.ghd.dataviz.mapper.UserMapper;
import com.ghd.dataviz.param.UserPageParam;
import com.ghd.dataviz.service.IUserService;
import com.ghd.dataviz.utils.PageUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author guohd
 * @since 2020-03-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource(name = "passwordEncoder")
    private PasswordEncoder passwordEncoder;

    @Override
    public User findByName(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getName, name).eq(User::getStatus, 1).last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public User addUser(User user) {
        User existUser = this.getOne(lambdaQuery()
                .eq(User::getName, user.getName()).last("limit 1"));
        if (existUser != null) {
            throw new BusinessException("用户已经存在！");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.save(user);
        return user;
    }

    @Override
    public PageInfo<User> findUserPageList(UserPageParam pageParam) {
        Page<User> page = PageUtil.convertParam(pageParam);
        String name = pageParam.getName() + "%";
        Page<User> users = this.baseMapper.findUserPageList(page, name);
        return PageUtil.convertPage(users);
    }
}
